package com.flxz.user.service.impl;

import com.flxz.common.constant.CacheConstants;
import com.flxz.common.core.domain.entity.SysUser;
import com.flxz.common.core.redis.RedisCache;
import com.flxz.common.utils.DateUtils;
import com.flxz.user.domain.UserSignIn;
import com.flxz.user.domain.vo.SignInInfoVO;
import com.flxz.user.domain.vo.UserProfileVO;
import com.flxz.user.mapper.UserSignInMapper;
import com.flxz.user.service.IUserProfileService;
import com.flxz.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 用户个人信息Service业务层处理
 */
@Service
public class UserProfileServiceImpl implements IUserProfileService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private UserSignInMapper userSignInMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public UserProfileVO getUserProfile(Long userId) {
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (sysUser == null) {
            return null;
        }

        UserProfileVO userProfileVO = new UserProfileVO();
        BeanUtils.copyProperties(sysUser, userProfileVO);

        // 设置扩展字段
        userProfileVO.setFixedIncome(sysUser.getMonthlyIncome() != null ? BigDecimal.valueOf(sysUser.getMonthlyIncome()) : BigDecimal.ZERO);
        userProfileVO.setExpectedExpense(sysUser.getMonthlyExpense() != null ? BigDecimal.valueOf(sysUser.getMonthlyExpense()) : BigDecimal.ZERO);

        return userProfileVO;
    }

    @Override
    public int updateUserProfile(UserProfileVO userProfileVO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userProfileVO, sysUser);
        
        // 设置扩展字段
        sysUser.setMonthlyIncome(userProfileVO.getFixedIncome() != null ? userProfileVO.getFixedIncome().doubleValue() : 0.0);
        sysUser.setMonthlyExpense(userProfileVO.getExpectedExpense() != null ? userProfileVO.getExpectedExpense().doubleValue() : 0.0);
        
        return sysUserService.updateUser(sysUser);
    }

    @Override
    public int signIn(Long userId) {
        // 检查今日是否已签到
        UserSignIn existingSignIn = userSignInMapper.selectTodaySignIn(userId);
        if (existingSignIn != null) {
            throw new RuntimeException("今日已签到，请勿重复签到");
        }

        // 创建签到记录
        UserSignIn userSignIn = new UserSignIn();
        userSignIn.setUserId(userId);
        userSignIn.setSignDate(new Date());
        userSignIn.setCreateTime(DateUtils.getNowDate());

        int result = userSignInMapper.insertUserSignIn(userSignIn);
        
        // 签到成功后，清除相关缓存
        if (result > 0) {
            clearSignInCache(userId);
        }
        
        return result;
    }

    @Override
    public SignInInfoVO getSignInInfo(Long userId) {
        // 构建缓存键
        String cacheKey = CacheConstants.USER_SIGNIN_KEY + userId;
        
        // 尝试从缓存获取
        SignInInfoVO cachedInfo = redisCache.getCacheObject(cacheKey);
        if (cachedInfo != null) {
            return cachedInfo;
        }
        
        // 缓存未命中，从数据库查询
        // 获取本月签到次数
        int signCount = userSignInMapper.countMonthSignIn(userId);

        // 检查今日是否已签到
        UserSignIn todaySignIn = userSignInMapper.selectTodaySignIn(userId);
        boolean signedToday = todaySignIn != null;

        SignInInfoVO signInInfo = new SignInInfoVO(signCount, signedToday);
        
        // 缓存结果，设置过期时间为1小时
        redisCache.setCacheObject(cacheKey, signInInfo, 3600, TimeUnit.SECONDS);
        
        return signInInfo;
    }

    /**
     * 清除用户签到相关缓存
     */
    private void clearSignInCache(Long userId) {
        String cacheKey = CacheConstants.USER_SIGNIN_KEY + userId;
        redisCache.deleteObject(cacheKey);
    }

}
